<?php
namespace App\Http\Controllers\Tool;

use App\Http\Controllers\Controller;
use App\Models\HongBao\HongBao;
use App\Models\Post\PostSta;
use App\Models\Tool\District;
use App\Models\Tool\Feedback;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;


class ToolController extends Controller
{


    /**
     * 版本控制
     */
    public function version()
    {
        return $this->sendSuccessResponse([
            'android_newest_version' => '23',
            'android_lowest_version' => '23',
            'ios_newest_version' => '1.90',
            'ios_lowest_version' => '1.90',
            'district_version' => '6',
        ]);
    }

    /**
     * 静态数据接口
     * @return \Illuminate\Http\JsonResponse
     */
    public function statisticsData(){
        return $this->sendSuccessResponse([
            'agreement_url' => 'http://beboy.me/agreement',
            'management_url' => 'http://beboy.me/management',
            'complaint_url' => 'http://beboy.me/complaint',
            'version' => [
                'android_newest_version' => '24',
                'android_lowest_version' => '23',
                'android_manager_newest_version' => '2',
                'android_manager_lowest_version' => '2',
                'ios_newest_version' => '1.98',
                'ios_lowest_version' => '1.90',
                'ios_manager_newest_version' => '1.0',
                'ios_manager_lowest_version' => '1.0',
                'district_version' => '6',
            ],
            'IOS' => [
                'version' => '2.00',
                'flag' => 1
            ],
            'activity'=>[
                'i_want_cash' => [
                    'flag' => 1,
                    'logo' => 'https://beboy.oss-cn-shanghai.aliyuncs.com/image/161570ef012eb98a700021116aa92d29.png'
                ]
            ],
            'release' => [
                'android' => 'http://api.beboy.me/release/beboy-release.apk'
            ],
            'public_districts' => DB::select("SELECT * FROM districts WHERE `public`=1")
        ]);
    }

    /**
     * 地区数据
     */
    public function district()
    {
        $data = DB::select("SELECT * FROM districts");
        return $this->sendSuccessResponse($data);
    }

    /**
     * 通过坐标获得城市和地区（小程序）
     * @param Request $request
     * @param Client $client
     * @param District $district
     * @return \Illuminate\Http\JsonResponse
     */
    public function locationToDistrict(Request $request, Client $client, District $district)
    {
        $validator = Validator::make($request->all(), [
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
        ], [
            'latitude.required' => '10001',
            'latitude.numeric' => '10002',
            'longitude.required' => '10001',
            'longitude.numeric' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $map_api = 'http://apis.map.qq.com/ws/geocoder/v1/';
        $key = 'AGOBZ-3PAWS-7QQO3-6LPPW-UGE3E-M5BKA';//大众点评key:'I3OBZ-MBSRQ-WBJ5P-G5VZS-QGAIF-Y7B27'
        $location = $request['latitude'].','.$request['longitude'];
        $rs = $client->get($map_api.'?location='.$location.'&key='.$key);
        $data = json_decode($rs->getBody(), true);
        if(empty($data['result']['address_component']['city'])){
            Log::debug('Fail no city lat='.$request['latitude'].',lng='.$request['longitude']);
            return $this->sendFailResponse(400,'no city data');
        }
        $city_data = $district->where('type',2)->where('name', $data['result']['address_component']['city'])->first();
        if(empty($city_data)){
            Log::debug('Fail no city name='.$data['result']['address_component']['city']);
            return $this->sendFailResponse(400,'no city name');
        }
        $district_data = $district->where('name',$data['result']['address_component']['district'])->where('parent_id',$city_data['id'])->first();
        if(empty($district_data)){
            if($data['result']['address_component']['city']=='东莞市'){
                $district_data = $district->find(441999);
            }elseif($data['result']['address_component']['city']=='中山市'){
                $district_data = $district->find(442099);
            }else{
                Log::debug('Fail no district name='.$data['result']['address_component']['district']);
                return $this->sendFailResponse(400,'no district name');
            }
        }
        $province_data = $district->getById($city_data['parent_id']);
        return $this->sendSuccessResponse([
            'province_id' => $province_data['id'],
            'province_name' => $province_data['name'],
            'city_id' => $city_data['id'],
            'city_name' => $city_data['name'],
            'district_id' => $district_data['id'],
            'district_name' => $district_data['name'],
        ]);
    }

    /**
     * 开放城市列表（小程序）
     * @return \Illuminate\Http\JsonResponse
     */
    public function publicCities(District $district){
        $letters = ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"];
        $city = [];
        foreach($letters as $letter) {
            $result = $district->select('id','name')->where('public', 1)->where('type', 2)->where('first_letter', $letter)->orderBy('priority', 'desc')->orderBy('id', 'asc')->get();
            if($result->count()){
                $city[$letter] = $result;
            }
        }
        return $this->sendSuccessResponse([
            'public_cities' => $city
        ]);
    }

    /**
     * 分享数据
     * @return \Illuminate\Http\JsonResponse
     */
    public function shareData()
    {
        return $this->sendSuccessResponse([
            'share_url' => 'http://beboy.me/share?origin='.Auth::id().'_'.time(),
            'share_text' => '夜城娱乐，让你每一天，越夜越精彩',
            'share_title' => '奔波在都市的繁忙，夜要享受迷人的繁华~',
            'share_logo' => 'http://beboy.oss-cn-shanghai.aliyuncs.com/image/3c5d7f55cb761e4b08ce5d3603bda9f7.png',
        ]);
    }

    /**
     * 帖子分享后回调
     * @param $id
     * @param PostSta $sta
     * @param HongBao $hong_bao
     * @return \Illuminate\Http\JsonResponse
     */
    public function shared($id, PostSta $sta, HongBao $hong_bao){
        $valid_data['id'] = $id;
        $validator = Validator::make($valid_data, [
            'id' => 'required|integer',
        ], [
            'id.required' => '10001',
            'id.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        //todo 检查帖子
        $sta->where('post_id', $id)->increment('shared');
        $code = $hong_bao->addConfigHongBao('shared_hong_bao_template', Auth::id(), 'post_'.$id);
        if($code != 200){
            return $this->sendSuccessResponse([
                'hong_bao' => 0,
                'code' => $code
            ]);
        }
        return $this->sendSuccessResponse([
            'hong_bao' => 1,
            'code' => 200
        ]);
    }

    /**
     * 反馈
     * @param Feedback $feedBack
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function feedback(Feedback $feedBack, Request $request){
        $validator = Validator::make($request->all(), [
            'device' => 'required|string|max:200',
            'version' => 'required|string|max:10',
            'content' => 'required|string|max:500',
            'contact' => 'required|string|max:50',
        ], [
            'device.required' => '10001',
            'device.string' => '10002',
            'device.max' => '10002',
            'version.required' => '10001',
            'version.string' => '10002',
            'version.max' => '10002',
            'content.required' => '10001',
            'content.string' => '10002',
            'content.max' => '10002',
            'contact.required' => '10001',
            'contact.string' => '10002',
            'contact.max' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $feedBack->user_id = Auth::id();
        $feedBack->device = $request['device'];
        $feedBack->version = $request['version'];
        $feedBack->content = $request['content'];
        $feedBack->contact = $request['contact'];
        $feedBack->save();
        return $this->sendSuccessResponse([]);
    }
}